import AMap from 'AMap';

export const getGeolocation = (config={}) => {
    return new Promise((resolve,reject) => {
        AMap.plugin('AMap.Geolocation', function() {
            var geolocation = new AMap.Geolocation({
                // 是否使用高精度定位，默认：true
                enableHighAccuracy: true,
                // 设置定位超时时间，默认：无穷大
                timeout: 10000,
                ...config
            })
        
            geolocation.getCurrentPosition()
            AMap.event.addListener(geolocation, 'complete', onComplete)
            AMap.event.addListener(geolocation, 'error', onError)
        
            function onComplete (data) {
                // data是具体的定位信息
                resolve(data);
            }
        
            function onError (data) {
                // 定位出错
                reject(data)
            }
        })
    })
}


export const autocomplete = function(keyword,city='北京'){
    return new Promise((resolve,reject) => {
        AMap.plugin('AMap.Autocomplete', function(){
            // 实例化Autocomplete
            var autoOptions = {
                //city 限定城市，默认全国
                city
            }
            var autoComplete= new AMap.Autocomplete(autoOptions);
            autoComplete.search(keyword, function(status, result) {
                // 搜索成功时，result即是对应的匹配数据
                if(status === 'complete'){
                    //成功
                    resolve(result);
                }else{
                    //失败
                    reject(result);
                }
            })
        })
    })   
}
